/**
 * 书签控制器
 * 处理书签的创建、读取、更新、删除和导入操作
 */

const Bookmark = require('../models/Bookmark');
const Category = require('../models/Category');
const cheerio = require('cheerio');

/**
 * @desc    获取所有书签
 * @route   GET /api/bookmarks
 * @access  公开
 */
exports.getBookmarks = async (req, res) => {
  try {
    // 查询参数
    const { category, tag, search, sort, limit = 100, page = 1 } = req.query;
    
    // 构建查询条件
    let query = {};
    
    // 按分类筛选
    if (category) {
      query.category = category;
    }
    
    // 按标签筛选
    if (tag) {
      query.tags = tag;
    }
    
    // 搜索功能
    if (search) {
      query.$or = [
        { title: { $regex: search, $options: 'i' } },
        { description: { $regex: search, $options: 'i' } },
        { url: { $regex: search, $options: 'i' } }
      ];
    }
    
    // 计算分页
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    const total = await Bookmark.countDocuments(query);
    
    // 排序选项
    let sortOption = {};
    if (sort) {
      const parts = sort.split(':');
      sortOption[parts[0]] = parts[1] === 'desc' ? -1 : 1;
    } else {
      sortOption = { createdAt: -1 }; // 默认按创建时间降序
    }
    
    // 执行查询
    const bookmarks = await Bookmark.find(query)
      .populate('category', 'name icon color')
      .sort(sortOption)
      .skip(startIndex)
      .limit(parseInt(limit));
    
    // 构建分页结果
    const pagination = {};
    
    if (endIndex < total) {
      pagination.next = {
        page: page + 1,
        limit
      };
    }
    
    if (startIndex > 0) {
      pagination.prev = {
        page: page - 1,
        limit
      };
    }
    
    res.status(200).json({
      success: true,
      count: bookmarks.length,
      pagination,
      total,
      data: bookmarks
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: '无法获取书签'
    });
  }
};

/**
 * @desc    获取单个书签
 * @route   GET /api/bookmarks/:id
 * @access  公开
 */
exports.getBookmark = async (req, res) => {
  try {
    const bookmark = await Bookmark.findById(req.params.id).populate('category', 'name icon color');
    
    if (!bookmark) {
      return res.status(404).json({
        success: false,
        message: '找不到该书签'
      });
    }
    
    res.status(200).json({
      success: true,
      data: bookmark
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: '无法获取书签'
    });
  }
};

/**
 * @desc    创建书签
 * @route   POST /api/bookmarks
 * @access  私有 (仅管理员)
 */
exports.createBookmark = async (req, res) => {
  try {
    // 检查分类是否存在
    const category = await Category.findById(req.body.category);
    
    if (!category) {
      return res.status(400).json({
        success: false,
        message: '指定的分类不存在'
      });
    }
    
    const bookmark = await Bookmark.create(req.body);
    
    res.status(201).json({
      success: true,
      data: bookmark
    });
  } catch (err) {
    res.status(400).json({
      success: false,
      message: err.message
    });
  }
};

/**
 * @desc    更新书签
 * @route   PUT /api/bookmarks/:id
 * @access  私有 (仅管理员)
 */
exports.updateBookmark = async (req, res) => {
  try {
    // 如果更新包含分类，检查分类是否存在
    if (req.body.category) {
      const category = await Category.findById(req.body.category);
      
      if (!category) {
        return res.status(400).json({
          success: false,
          message: '指定的分类不存在'
        });
      }
    }
    
    const bookmark = await Bookmark.findByIdAndUpdate(
      req.params.id,
      req.body,
      {
        new: true,
        runValidators: true
      }
    ).populate('category', 'name icon color');
    
    if (!bookmark) {
      return res.status(404).json({
        success: false,
        message: '找不到该书签'
      });
    }
    
    res.status(200).json({
      success: true,
      data: bookmark
    });
  } catch (err) {
    res.status(400).json({
      success: false,
      message: err.message
    });
  }
};

/**
 * @desc    删除书签
 * @route   DELETE /api/bookmarks/:id
 * @access  私有 (仅管理员)
 */
exports.deleteBookmark = async (req, res) => {
  try {
    // 验证ID格式
    if (!req.params.id.match(/^[0-9a-fA-F]{24}$/)) {
      return res.status(400).json({
        success: false,
        message: '无效的书签ID'
      });
    }

    const bookmark = await Bookmark.findById(req.params.id);
    
    if (!bookmark) {
      return res.status(404).json({
        success: false,
        message: '找不到该书签'
      });
    }

    // 使用deleteOne而不是remove
    await Bookmark.deleteOne({ _id: req.params.id });
    
    res.status(200).json({
      success: true,
      data: {}
    });
  } catch (err) {
    console.error('删除书签时出错:', err);
    res.status(500).json({
      success: false,
      message: err.message || '无法删除书签'
    });
  }
};

/**
 * @desc    增加书签点击次数
 * @route   PUT /api/bookmarks/:id/click
 * @access  公开
 */
exports.incrementClickCount = async (req, res) => {
  try {
    const bookmark = await Bookmark.findById(req.params.id);
    
    if (!bookmark) {
      return res.status(404).json({
        success: false,
        message: '找不到该书签'
      });
    }
    
    await bookmark.incrementClickCount();
    
    res.status(200).json({
      success: true,
      data: bookmark
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: '无法更新点击次数'
    });
  }
};

/**
 * @desc    获取所有标签
 * @route   GET /api/bookmarks/tags
 * @access  公开
 */
exports.getTags = async (req, res) => {
  try {
    // 聚合查询获取所有唯一标签及其使用次数
    const tags = await Bookmark.aggregate([
      { $unwind: '$tags' },
      { $group: { _id: '$tags', count: { $sum: 1 } } },
      { $sort: { count: -1 } }
    ]);
    
    res.status(200).json({
      success: true,
      count: tags.length,
      data: tags.map(tag => ({ name: tag._id, count: tag.count }))
    });
  } catch (err) {
    res.status(500).json({
      success: false,
      message: '无法获取标签'
    });
  }
};

/**
 * @desc    批量创建书签
 * @route   POST /api/bookmarks/batch
 * @access  私有 (仅管理员)
 */
exports.createBookmarksBatch = async (req, res) => {
  try {
    const { bookmarks } = req.body;
    
    if (!Array.isArray(bookmarks) || bookmarks.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供有效的书签数组'
      });
    }
    
    // 验证所有分类是否存在
    const categoryIds = [...new Set(bookmarks.map(b => b.category))];
    const categories = await Category.find({ _id: { $in: categoryIds } });
    
    if (categories.length !== categoryIds.length) {
      return res.status(400).json({
        success: false,
        message: '一个或多个指定的分类不存在'
      });
    }
    
    // 批量创建书签
    const createdBookmarks = await Bookmark.insertMany(bookmarks);
    
    res.status(201).json({
      success: true,
      count: createdBookmarks.length,
      data: createdBookmarks
    });
  } catch (err) {
    res.status(400).json({
      success: false,
      message: err.message
    });
  }
};

/**
 * @desc    解析并导入HTML书签
 * @route   POST /api/bookmarks/import/html
 * @access  私有 (仅管理员)
 */
exports.importBookmarksFromHtml = async (req, res) => {
  try {
    const { html, defaultCategoryId } = req.body;
    
    if (!html) {
      return res.status(400).json({
        success: false,
        message: '请提供HTML内容'
      });
    }
    
    // 检查默认分类是否存在
    if (defaultCategoryId) {
      const category = await Category.findById(defaultCategoryId);
      
      if (!category) {
        return res.status(400).json({
          success: false,
          message: '指定的默认分类不存在'
        });
      }
    }
    
    // 解析HTML
    const $ = cheerio.load(html);
    const bookmarks = [];
    
    // 递归解析书签文件夹和链接
    const parseFolder = (element, categoryId) => {
      // 获取文件夹中的所有链接
      $(element).find('> a').each((i, link) => {
        const title = $(link).text().trim();
        const url = $(link).attr('href');
        const addDate = $(link).attr('add_date');
        
        if (url && title) {
          bookmarks.push({
            title,
            url,
            category: categoryId || defaultCategoryId,
            createdAt: addDate ? new Date(parseInt(addDate) * 1000) : new Date()
          });
        }
      });
      
      // 递归处理子文件夹
      $(element).find('> dl > dt').each((i, subFolder) => {
        const folderTitle = $(subFolder).find('> h3').first().text().trim();
        
        if (folderTitle) {
          // 这里可以创建新的分类，但为简单起见，我们使用默认分类
          parseFolder(subFolder, categoryId || defaultCategoryId);
        }
      });
    };
    
    // 从根开始解析
    $('dl > dt').each((i, folder) => {
      parseFolder(folder, defaultCategoryId);
    });
    
    // 返回解析结果，但不保存到数据库
    res.status(200).json({
      success: true,
      count: bookmarks.length,
      data: bookmarks
    });
  } catch (err) {
    res.status(400).json({
      success: false,
      message: '解析HTML失败: ' + err.message
    });
  }
}; 